package com.example.java.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class CustomConsumerGroup {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                KafkaConsumer<String, String> kafkaConsumer = CustomConsumerGroup.getCustomConsumerGroup();
                kafkaConsumer.subscribe(Collections.singletonList("consumer1")); // 订阅主题
                while (true) {
                    ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));
                    for (ConsumerRecord<String, String> record : records) {
                        System.out.printf(kafkaConsumer + " 消费消息: partition = %d, offset = %d, key = %s, value = %s%n", record.partition(), record.offset(), record.key(), record.value());
                    }
                }
            }).start();
        }
    }

    private static KafkaConsumer<String, String> getCustomConsumerGroup() {
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer_group"); // 配置消费者组
        // 可选：设置自动提交 offset
        properties.put("enable.auto.commit", "true");
        properties.put("auto.commit.interval.ms", "1000");
        return new KafkaConsumer<>(properties);
    }
}